package com.droidexchange.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.sf.stackwrap4j.StackWrapper;
import android.content.Context;
import android.os.Debug;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.Toast;

public final class Util
{
	public static StackWrapper	sw	= null;

	private static boolean isDebugEnabled = false;
	private static long startTime;
	private static HashMap<String, Long> timeMap = new HashMap<String, Long>();

	public void shortToast(Context context, int resId)
	{
		Toast.makeText(context, resId, Toast.LENGTH_SHORT).show();
	}

	public void shortToast(Context context, String msg)
	{
		Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
	}

	public void sleep(long t)
	{
		try
		{
			Thread.sleep(t);
		}
		catch (InterruptedException ex)
		{
			Logger.getLogger(Util.class.getName()).log(Level.SEVERE, null, ex);
		}
	}

	public String getFileExt(String filename)
	{
		int n = filename.lastIndexOf(".");
		return filename.substring(n + 1, filename.length());
	}

	public String getFileName(String filepath)
	{
		int n = filepath.lastIndexOf("/");
		return filepath.substring(n + 1, filepath.length());
	}

	public String getFilePath(String filepath)
	{
		if (filepath.endsWith(Const.SEP))
			filepath = filepath.substring(0, filepath.lastIndexOf(Const.SEP));

		int n = filepath.lastIndexOf("/");
		return filepath.substring(0, n);
	}

	public HashMap<String, String> splitToMap(String original, String separator, String elemSep)
	{
		HashMap<String, String> infoMap = null;
		String[] elems = split(original, elemSep);
		if (elems.length <= 0)
			return null;

		infoMap = new HashMap<String, String>();
		for (int i = 0; i < elems.length; i++)
		{
			String[] keyValue = split(elems[i], separator);
			if (keyValue.length >= 2)
			{
				String key = keyValue[0];
				String value = keyValue[1];
				// if (key != null && value != null)
				infoMap.put(key, value);
			}
		}

		if (infoMap.isEmpty())
			infoMap = null;

		return infoMap;
	}

	public static String[] split(String original, String separator)
	{
		ArrayList<String> nodes = new ArrayList<String>();

		// Parse nodes into vector
		int index = original.indexOf(separator);
		while (index >= 0)
		{
			String str = original.substring(0, index);
			if (str != null)
			{
				str = str.trim();
				if (str.length() > 0)
				{
					nodes.add(str);
				}
			}

			original = original.substring(index + separator.length());
			index = original.indexOf(separator);
		}

		// Get the last node
		if (original != null)
		{
			original = original.trim();
			if (original.length() > 0)
			{
				nodes.add(original);
			}
		}

		// Create splitted string array
		String[] result = new String[nodes.size()];
		if (nodes.size() > 0)
		{
			for (int loop = 0; loop < nodes.size(); loop++)
			{
				result[loop] = (String) nodes.get(loop);
			}
		}

		nodes.clear();
		nodes = null;
		return result;
	}

	/*
	 * To convert the InputStream to String we use the BufferedReader.readLine()
	 * method. We iterate until the BufferedReader return null which means
	 * there's no more data to read. Each line will appended to a StringBuilder
	 * and returned as String.
	 */
	public static String convertStreamToString(InputStream is)
	{
		try
		{
			if (is != null)
			{
				StringBuilder sb = new StringBuilder();
				String line;

				try
				{
					BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
					while ((line = reader.readLine()) != null)
					{
						sb.append(line).append("\n");
					}
				}
				finally
				{
					is.close();
				}

				return sb.toString();
			}
		}
		catch (Exception e)
		{
			Logger.getAnonymousLogger().log(Level.SEVERE, null, e);
		}

		return "";
	}

	public String getNow()
	{
		return Long.toHexString(Calendar.getInstance().getTimeInMillis());
	}

	/** Show an event in the LogCat view, for debugging */
	public void dumpEventLog(MotionEvent event)
	{
		String names[] = { "DOWN", "UP", "MOVE", "CANCEL", "OUTSIDE", "POINTER_DOWN", "POINTER_UP", "7?", "8?", "9?" };
		StringBuilder sb = new StringBuilder();
		int action = event.getAction();
		int actionCode = action & MotionEvent.ACTION_MASK;
		sb.append("event ACTION_").append(names[actionCode]);
		if (actionCode == MotionEvent.ACTION_POINTER_DOWN || actionCode == MotionEvent.ACTION_POINTER_UP)
		{
			sb.append("(pid ").append(action >> MotionEvent.ACTION_POINTER_ID_SHIFT);
			sb.append(")");
		}

		sb.append("[");
		for (int i = 0; i < event.getPointerCount(); i++)
		{
			sb.append("#").append(i);
			sb.append("(pid ").append(event.getPointerId(i));
			sb.append(")=").append((int) event.getX(i));
			sb.append(",").append((int) event.getY(i));
			if (i + 1 < event.getPointerCount())
				sb.append(";");
		}
		sb.append("]");
		Log.d(Const.TAG, sb.toString());
	}

	public boolean validateEmail(String email)
	{
		// Set the email pattern string
		Pattern p = Pattern.compile(".+@.+\\.[a-z]+");

		// Match the given string with the pattern
		Matcher m = p.matcher(email);

		// check whether match is found
		return m.matches();
	}

	public String urlEncode(String orig)
	{
		if (orig == null)
			return null;

		return URLEncoder.encode(orig);
	}

	public String urlDecode(String orig)
	{
		if (orig == null)
			return null;

		return URLDecoder.decode(orig);
	}

	public static void log(String s)
	{
		Log.i(Const.TAG, " ===================>>>>>>> " + s);
	}

	public static void _resetTime()
	{
		startTime = System.currentTimeMillis();
		timeMap.clear();
		Util.log(" ======>>> STARTING LOG");
	}

	//printTimeSince
	public static void _pts(int key)
	{
		_pts(Integer.toString(key));
	}
	
	//printTimeSince
	public static void _pts(String key)
	{
		long now = System.currentTimeMillis();
		startTime = now - startTime;
		Util.log(" ======>>> time " + key + " = " + startTime + " ms");
		long iii = 0;
		if (timeMap.containsKey(key))
			iii = timeMap.get(key);
		timeMap.put(key, iii + startTime);
		startTime = now;
	}

	public static void _finalize()
	{
		Iterator<String> itr = timeMap.keySet().iterator();
		Util.log(" ======>>> STARTING LOG PRINTING");
		while(itr.hasNext())
		{
			String key = itr.next();
			log(key + " ----- " + timeMap.get(key));
		}
		Util.log(" ======>>> ENDING LOG");
	}
	
	public static void waitForDebugger()
	{
		if (isDebugEnabled)
			return;
		
		isDebugEnabled = true;
		Debug.waitForDebugger();
	}
}
